package com.tiance.demo.observer;

import java.util.HashMap;
import java.util.Map;
import java.util.Observer;

/**
 * 监听系统
 */
public class ObserverSystem {


    private static Map<ObserverEvent, Publisher> observerMap = new HashMap<>();

//    private static Map<Publisher, List<Subscriber>> observerMap = new HashMap<>();

//    public static <ObserverEvent> List<Subscriber> registerObservable(ObserverEvent oe) {
//        Publisher<ObserverEvent> publisher = new Publisher<>(oe);
//
//        return observerMap.computeIfAbsent(publisher, k -> new ArrayList<>());
//    }

    public static boolean registerObserver(ObserverEvent oe, Observer observer) {
        Publisher publisher = null;
        for (Map.Entry<ObserverEvent, Publisher> entry : observerMap.entrySet()) {
            if (oe == entry.getKey()) {
                publisher = entry.getValue();
                break;
            }
        }

        if (publisher == null) {
            publisher = new Publisher(oe);
            observerMap.put(oe, publisher);
        }

        return publisher.addSubscriber(observer);
    }

    public static void notifyObservers(ObserverEvent oe, ObserverData od) {
        Publisher publisher = observerMap.get(oe);
        if (publisher == null) {
            return;
        }

        publisher.notifyWithData(od);
    }
}
